const { src, dest, parallel, watch, series } = require("gulp")
const gulpClean = require("gulp-clean-css")
const autoprefixer = require("gulp-autoprefixer")
const rename = require("gulp-rename")
const uglify = require("gulp-uglify")
const babel = require("gulp-babel")
const htmlMin = require("gulp-htmlmin")
const imageMIn = require("gulp-imagemin")
const browserSync = require("browser-sync")
const bs = browserSync.create()
const del = require("del")



const style = () => {
    return src("src/css/**.css", { base: "src" })
        .pipe(autoprefixer())
        .pipe(gulpClean())
        .pipe(rename({ extname: ".min.css" }))
        .pipe(dest("dist"))
}

const script = () => {
    return src("./src/lib/index.js", { base: "src" })
        .pipe(babel({ presets: ['babel-preset-env'] }))
        .pipe(uglify())
        .pipe(rename({ extname: ".min.js" }))
        .pipe(dest("dist"))
}

const html = () => {
    return src("src/index.html", { base: "src" })
        .pipe(htmlMin({
            collapseWhitespace: true,
            minifyCSS: true,
            minifyJS: true,
            minifyURLs: true
        }))
        .pipe(dest("dist"))
}
const json = () => {
    return src("src/zong/*.*", { base: "src" })
        .pipe(dest("dist"))
}

const image = () => {
    return src("src/images/*.*", {base : "src"})
    .pipe(imageMIn())
    .pipe(dest("dist"))
}

const serve = () => {
    watch("src/index.html", html)
    watch("src/css/*.css", style)
    watch("src/lib/index.js", script)
    watch("src/images/**", image)
    bs.init({
        notify: false,
        files: "dist/**",
        server: {
            baseDir: "./dist",
            routes: {
                "/node_modules": "node_modules"
            },
        },
    })
}

const clean = () => {
    return del(["dist"])
}

const build = parallel(html, script, style, json, image)
const dev = series(clean,build, serve)

module.exports = {
    dev
}